package org.jeecg.common.modules.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.modules.dic.service.IDicConstantsService;
import org.jeecg.common.modules.dic.util.DicConstant;
import org.jeecg.common.modules.sys.entity.SysAppUpgrade;
import org.jeecg.common.modules.sys.mapper.SysAppUpgradeMapper;
import org.jeecg.common.modules.sys.service.ISysAppUpgradeService;
import org.jeecg.common.modules.sys.vo.SysReqVo;
import org.jeecg.common.util.enums.AppPlatformEnum;
import org.jeecg.common.util.enums.AppUpgradeStrategyEnum;
import org.jeecg.common.util.enums.StatusEnum;
import org.jeecg.common.util.result.Result;
import org.jeecg.common.util.result.ResultMapper;
import org.jeecg.common.util.upgrade.AppUpgradeResponseVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author guoyh
 * @ClassName SysAppUpgradeServiceImpl
 * @Description
 * @since 2020/9/6 15:55
 **/
@Service
@Slf4j
public class SysAppUpgradeServiceImpl extends ServiceImpl<SysAppUpgradeMapper, SysAppUpgrade> implements ISysAppUpgradeService {

    @Resource
    private IDicConstantsService dicConstantsService;

    @Resource
    private SysAppUpgradeMapper sysAppUpgradeMapper;


    @Override
    public Result<AppUpgradeResponseVo> checkVersion(String platform, String version){
        if (StringUtils.isBlank(platform) || StringUtils.isBlank(version)){
            return ResultMapper.illegalArgument();
        }
        AppPlatformEnum platformEnum = AppPlatformEnum.valueOf(platform);
        if (Objects.isNull(platformEnum)){
            return ResultMapper.<AppUpgradeResponseVo>error().setMsg("未知的平台类型");
        }
        String[] versions = version.split("\\.");
        if (Objects.isNull(versions) || versions.length != 3){
            return ResultMapper.<AppUpgradeResponseVo>error().setMsg("非法的版本号");
        }
        Version appVersion = null;
        try {
            appVersion = new Version(versions);
        } catch (Exception e) {
            log.error("转换version异常,platform:{}version:{}",platform,version,e);
            return ResultMapper.<AppUpgradeResponseVo>error().setMsg("非法的版本号");
        }
        String audit = dicConstantsService.getByKey(DicConstant.APP_AUDIT);
        LambdaQueryWrapper<SysAppUpgrade> query = Wrappers.lambdaQuery();
        query.eq(SysAppUpgrade::getPlatformId,platformEnum.ordinal());
        query.ge(SysAppUpgrade::getVersion1,appVersion.getVersion1());
        query.last(" order by version_1 desc ,version_2 desc,version_3 desc ");
        List<SysAppUpgrade> list = list(query);
        list = filter(list,appVersion);
        if (CollectionUtils.isEmpty(list)){
            return ResultMapper.<AppUpgradeResponseVo>ok().setData(AppUpgradeResponseVo.buildNone(Integer.parseInt(audit)));
        }
        SysAppUpgrade sysAppUpgrade =list.get(0);
        if (StringUtils.equals( sysAppUpgrade.getVersion(),version)){
            return ResultMapper.<AppUpgradeResponseVo>ok().setData(AppUpgradeResponseVo.buildNone(Integer.parseInt(audit)));
        }
        Boolean forceUpgrade = list.stream().anyMatch(SysAppUpgrade::getForceUpgrade);
        String url = sysAppUpgrade.getUrl();
        AppUpgradeResponseVo responseVo = new AppUpgradeResponseVo();
        responseVo.setUpgradeStrategy(AppUpgradeStrategyEnum.getInstance(forceUpgrade).getCode());
        responseVo.setUrl(url);
        responseVo.setIsAudit(Objects.equals(Integer.parseInt(audit), StatusEnum.VALID.getCode()));
        return ResultMapper.<AppUpgradeResponseVo>ok().setData(responseVo);
    }

    private List<SysAppUpgrade> filter(List<SysAppUpgrade> list, final Version appVersion){
        return list.stream().filter(item -> filterVersion(item,appVersion)).collect(Collectors.toList());
    }

    private boolean filterVersion(SysAppUpgrade sysAppUpgrade,final  Version version){
        return sysAppUpgrade.getVersion1() > version.getVersion1() ||
                sysAppUpgrade.getVersion2() > version.getVersion2() ||
                sysAppUpgrade.getVersion3() > version.getVersion3();
    }


    @Data
    private static class Version{
        private int version1;

        private int version2;

        private int version3;

        public Version(String[] version){
            this.version1 = Integer.parseInt(version[0]);
            this.version2 = Integer.parseInt(version[1]);
            this.version3 = Integer.parseInt(version[2]);
        }
    }

    @Override
    public List<SysReqVo> getSysInfo(BigInteger platformId, String platformName, Integer dataStart, Integer pageSize){
        return sysAppUpgradeMapper.selectSysInfo(platformId,platformName,dataStart,pageSize);
    }

    @Override
    public int getSysCount(BigInteger platformId, String platformName){
        return sysAppUpgradeMapper.getSysCount(platformId,platformName);
    }
}
